/*
 * JarManager.java
 *
 * Created on 14 de octubre de 2006, 1:24
 */

package ub.es.ubictionary.io;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;
import java.util.zip.ZipException;

/**
 *
 * @author aram
 */
public class JarManager {
    
    /** Creates a new instance of JarManager */
    private JarManager() {
    }
    
    /**
     *Crea un archivo jar con el nombre dado, metiendo los archivos del path dado
     */
    public static void createJar(String jarName){
        String sourcePath = "." + File.separator + IOUtil.path;
       try {
         BufferedInputStream origin = null;
         FileOutputStream dest = new FileOutputStream(jarName);
         JarOutputStream out = new JarOutputStream(new BufferedOutputStream(dest));
         
         Object[] files;
         files = getFiles(sourcePath, new ArrayList(), null);
         for (int i=0; i<files.length; i++) {
            String file = (String) files[i];
            File f = new File(sourcePath + File.separator + file);
            if(f.isDirectory()){
                //System.out.println("Adding: "+file);
                out.putNextEntry(new JarEntry(file + "/"));
                continue;
            }
            
            //System.out.println("Adding: "+file);
            FileInputStream fi = new  FileInputStream(sourcePath + File.separator + file);
            origin = new BufferedInputStream(fi);
            JarEntry entry = new JarEntry(file);
            out.putNextEntry(entry);
            int data;
            while((data = origin.read()) != -1) {
               out.write(data);
            }
            origin.close();
         }
         out.close();
      } catch(Exception e) {
         e.printStackTrace();
      }
        
        createJadForJar("Omnidic");
    }
    
    private static void createJadForJar(String jar){
        File f = new File(jar + ".jar");
        long tam = f.length();
        
        String [] lines = new String[8];
        lines[0] = "MIDlet-1: UBictionary, ,ub.es.ubictionary.logic.UBictionary";
        lines[1] = "MIDlet-Jar-Size: " + tam;
        lines[2] = "MIDlet-Jar-URL: Omnidic.jar";
        lines[3] = "MIDlet-Name: Omnidic";
        lines[4] = "MIDlet-Vendor: Aram Julhakyan";
        lines[5] = "MIDlet-Version: 1.0";
        lines[6] = "MicroEdition-Configuration: CLDC-1.0";
        lines[7] = "MicroEdition-Profile: MIDP-1.0";
        try {
            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(jar + ".jad"))));
            for(int i = 0; i<lines.length; i++){
                out.write(lines[i], 0, lines[i].length());
                out.write(0xA);
            }
            out.close();
            
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    
    
    private static Object[] getFiles(String path, ArrayList v, String originalPath){
        File f = new File(path);
        File [] fl = f.listFiles();
        for(int i = 0; i < fl.length; i++){
            if (fl[i].isDirectory()){
                if (originalPath == null)
                    getFiles(path + "/" + fl[i].getName(), v, fl[i].getName());
                else
                    getFiles(path + "/" + fl[i].getName(), v, originalPath + "/" + fl[i].getName());
                //continue;
            }
            if (originalPath != null)
                v.add(originalPath + "/" + fl[i].getName());
            else
                v.add(fl[i].getName());
        }
        
        Object [] ar = v.toArray();
        Arrays.sort(ar);
        return  ar;
        
    }
     
    
    /**
     *Extrae el contenido de un JAR dado al path indicado
     */
    public static void extractJar(String jarPath) throws FileNotFoundException, IOException{
            String destinationPath = "." + File.separator + IOUtil.path;
            JarFile jar = new JarFile(jarPath);
            Enumeration e = jar.entries();
            while (e.hasMoreElements()) {
                
                    JarEntry file = (JarEntry) e.nextElement();
                    
                    File f = new File( destinationPath + File.separator + file.getName());
                    if (file.isDirectory()) { // if its a directory, create it
                            f.mkdir();
                            continue;
                    }
                    
                    InputStream is = jar.getInputStream(file); 
                    FileOutputStream fos = new FileOutputStream(f);
                    while (is.available() > 0) {  
                            fos.write(is.read());
                    }
                    fos.close();
                    is.close();
            }
            jar.close();
       
        
    }

    
    
    public static void clearDirectory(){
        String path = IOUtil.path;
        File f = new File(path);
        Writer.deleteDirectory(f);
        f.mkdir();
    }
}
